<template>
  <div class="Breadcrumb">
    <template v-if="BreadcrumbList.length">
      <a-tag
        v-for="item in BreadcrumbList"
        :key="item.path"
        :color="item.path === route.path ? '#87d068' : ''"
        closable
        style="cursor: pointer"
        @click="changeRoute(item)"
        @close="removeBreadcrumb(item.path)"
      >
        {{ item.label }}
      </a-tag>
    </template>
  </div>
</template>

<script setup>
import { computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { breadcrumbStore } from "@/store/modules/breadcrumb.js";
import { userStore } from "@/store/modules/user.js";

const route = useRoute();
const router = useRouter();
const breadcrumb = breadcrumbStore();
const user = userStore();

// 使用计算属性来动态获取 BreadcrumbList
const BreadcrumbList = computed(() => breadcrumb.BreadcrumbList);

// 移除面包屑
const removeBreadcrumb = (path) => {
  breadcrumb.removeBreadcrumb(path);
};

// 切换路由并更新面包屑
const changeRoute = (item) => {
  if (item.path === "/index") {
    breadcrumb.$reset();
  } else {
    findParentKey(item.key);
    breadcrumb.selectedKeys = [item.key.toString()];
  }
  router.push(item.path);
};

// 查找父节点并添加 OpenKeys
const findParentKey = (key) => {
  user.menus.some((item) => {
    return item.children?.some((child) => {
      if (child.id === Number(key)) {
        breadcrumb.openKeys = [item.id.toString()];
        return true;
      }
    });
  });
};
</script>

<style lang="scss" scoped>
.Breadcrumb {
  width: 100%;
  padding: 10px;
  background-color: #eee;
}
</style>
